package Gui;

import java.awt.KeyEventDispatcher;
import java.awt.event.KeyEvent;

import javax.swing.JButton;

import Robot.RobotControl;
import Robot.RobotDirection;


public class KeyDispatcher implements KeyEventDispatcher {
	
//	private final static int MOUSE_PRESSED = MouseEvent.MOUSE_PRESSED;
//	private final static int MOUSE_RELEASED = MouseEvent.MOUSE_PRESSED;
	
	private RobotControl control;
	private boolean isEnabled = false;
	
	private JButton up;
	private JButton down;
	private JButton right;
	private JButton left;
	
	public KeyDispatcher(RobotControl control)
	{
		this.control = control;
	}
	
    public boolean dispatchKeyEvent(KeyEvent e) 
    {
    	JButton[] all = {up, down, left, right};
    	
    	if (isEnabled) {
	    	if(e.getID() == KeyEvent.KEY_PRESSED)
	        {
	    		for (JButton btn: all) {
	    			btn.getModel().setPressed(false);
	    		}
	    		
	        	switch(e.getKeyCode())
	        	{
	        		case KeyEvent.VK_UP:
	        			//outputLabel.setText("Up");
	        			control.setDriveDirection(RobotDirection.FORWARD);
	        			up.getModel().setPressed(true);
	        			break;
	        		case KeyEvent.VK_DOWN:
	        			//outputLabel.setText("Down");
	        			control.setDriveDirection(RobotDirection.BACKWARD);
	        			down.getModel().setPressed(true);
	        			break;
	        		case KeyEvent.VK_LEFT:
	        			//outputLabel.setText("Left");
	        			control.setDriveDirection(RobotDirection.LEFT);
	        			left.getModel().setPressed(true);
	        			break;
	        		case KeyEvent.VK_RIGHT:
	        			//outputLabel.setText("Right");
	        			control.setDriveDirection(RobotDirection.RIGHT);
	        			right.getModel().setPressed(true);
	        			break;
        			default:
        				break;
	        	}
	        	
	        }
	    	
	    	if(e.getID() == KeyEvent.KEY_RELEASED)
	        {
	    		for (JButton btn: all) {
	    			btn.getModel().setPressed(false);
	    		}
	    		
	    		int key = e.getKeyCode();
	    		
	    		if (key == KeyEvent.VK_UP || key == KeyEvent.VK_DOWN || key == KeyEvent.VK_LEFT || key == KeyEvent.VK_RIGHT)
	    		{
	    			//outputLabel.setText("None");
	    			control.setDriveDirection(RobotDirection.NONE);
	    		}    
	    
	        }
    	}
    	
        //Allow the event to be redispatched
        return false;
    }
    
    public void setEnabled(boolean enable) {
    	isEnabled = enable;
    }
    
	public void setUp(JButton btn) {
		up = btn;
	}
    
	public void setDown(JButton btn) {
		down = btn;
	}
    
	public void setLeft(JButton btn) {
		left = btn;
	}
    
	public void setRight(JButton btn) {
		right = btn;
	}
}
